package repository

import (
	"log"
	"palms/global"
	"palms/model"
	"xorm.io/xorm"
)

type TaskRepository interface {
	List(task model.Task, pageNo int, pageSize int) ([]model.Task, error)

	Get(id int64) (*model.Task, error)

	Create(task model.Task) (int64, error)

	Delete(id int64) error
}

func NewTaskRepository(engine *xorm.Engine) TaskRepository {
	return &taskRepository{
		engine: engine,
	}
}

type taskRepository struct {
	engine *xorm.Engine
}

func (r *taskRepository) UpdateTopic(room model.Room) error {
	_, err := r.engine.ID(room.Id).Update(room)
	if err != nil {
		log.Printf("更新群名称失败[roomId:%s]\n", room.Id)
		return err
	}
	return nil
}

func (r *taskRepository) List(task model.Task, pageNo int, pageSize int) ([]model.Task, error) {
	tasks := make([]model.Task, 0)
	err := global.Engine.
		Where("name like ? and startTime between ? and ?", task.Name, task.StartTime, task.EndTime).
		Limit(pageSize, pageNo*pageSize).
		Find(tasks)
	if err != nil {
		return nil, err
	}
	if err != nil {
		log.Println("查询任务信息列表失败" + err.Error())
		return nil, err
	}
	return []model.Task{}, err
}

func (r *taskRepository) Get(id int64) (*model.Task, error) {
	var task model.Task
	_, err := global.Engine.ID(id).Get(task)
	if err != nil {
		log.Println("查询任务信息失败" + err.Error())
		return nil, err
	}
	return &task, nil
}

func (r *taskRepository) Create(task model.Task) (int64, error) {
	t, err := r.engine.InsertOne(task)
	if err != nil {
		log.Println("保存任务信息失败" + err.Error())
		return 0, nil
	}
	return t, nil
}

func (r *taskRepository) Delete(id int64) error {
	_, err := r.engine.ID(id).Delete()
	if err != nil {
		log.Println("删除任务信息失败" + err.Error())
		return err
	}
	return nil
}
